package com.hui.controller.user;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hui.constant.ShopConstants;
import com.hui.entity.dao.ShopUser;
import com.hui.entity.dao.SystemGroupData;
import com.hui.entity.dao.UserBill;
import com.hui.entity.dto.SystemGroupDataQueryCriteria;
import com.hui.entity.enums.AppHttpCodeEnum;
import com.hui.entity.enums.BillDetailEnum;
import com.hui.entity.vo.SystemGroupDataVo;
import com.hui.handler.exception.SystemException;
import com.hui.model.user.RechargeParam;
import com.hui.service.SystemGroupDataService;
import com.hui.service.UserBillService;
import com.hui.service.UserRechargeService;
import com.hui.service.UserService;
import com.hui.util.ResponseResult;
import com.hui.util.module.GetUserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户充值前端控制器
 */
@RestController
@CrossOrigin
@RequiredArgsConstructor
@Slf4j
@RequestMapping("/api/recharge")
public class UserRechargeController {

    private final SystemGroupDataService systemGroupDataService; //组合数据详情表(SystemGroupData)
    private final UserService userService; //用户表
    private final UserRechargeService userRechargeService; //用户充值表
    private final UserBillService userBillService;

    /**
     * 充值方案
     */
    @GetMapping("/index")
    //(value = "充值方案",notes = "充值方案")
    public ResponseResult getWays() {
        /**
         * TODO  SystemGroupDataQueryCriteria 这个类用途不明
         *
         */
        SystemGroupDataQueryCriteria queryCriteria = new SystemGroupDataQueryCriteria();
        queryCriteria.setGroupName(ShopConstants.YSHOP_RECHARGE_PRICE_WAYS);
        List<SystemGroupData> systemGroupDataList = systemGroupDataService.queryAll(queryCriteria);

        List<SystemGroupDataVo> systemGroupDataVoList = systemGroupDataList.stream().map(s -> {
            SystemGroupDataVo systemGroupDataVo = new SystemGroupDataVo();
            BeanUtil.copyProperties(s, systemGroupDataVo, "value");
            systemGroupDataVo.setValue(JSON.parseObject(s.getValue()));
            return systemGroupDataVo;
        }).collect(Collectors.toList());

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("rechargePriceWays", systemGroupDataVoList);
        return ResponseResult.okResult(map);
    }

    /**
     * 模拟充值
     */
    @PostMapping("/test")
    public ResponseResult addTest(@RequestBody RechargeParam param, HttpServletRequest request) {
        //获取用户
        Long uid = GetUserInfo.getUid(request);
        ShopUser user = userService.getById(uid);
        // 通过传过来的充值方案ID查找
        SystemGroupData systemGroupData = systemGroupDataService.getById(param.getRecharId());
        if (systemGroupData == null) {
            throw new SystemException(AppHttpCodeEnum.NO_PARAMETE_OPERATE.getCode(), "充值方案不存在");
        }
        JSONObject jsonObject = JSON.parseObject(systemGroupData.getValue());
        // 充值金额
        String price = jsonObject.getString("price");
        // 赠送金额
        String giveMoney = jsonObject.getString("give_price");
        // 根据充值方案，充值到账户
        String orderSn = userRechargeService.addRecharge(user, price, giveMoney);
        // 订单号不为空进入充值
        if (orderSn != null) {
            // 充值金额
            BigDecimal new_price = new BigDecimal(price);
            // 赠送金额
            BigDecimal new_giveMoney = new BigDecimal(giveMoney);
            // 总计充值金额
            BigDecimal total = new_price.add(new_giveMoney);
            // 用当前余额加上充值总金额
            BigDecimal balance = user.getNowMoney().add(total);
            // 实体类赋值用户余额
            user.setNowMoney(balance);
            // 更新用户信息
            userService.updateById(user);
            // 往账单表插入充值记录
            UserBill userBill = new UserBill();
            // 用户ID
            userBill.setUid(user.getUid());
            // 账单标题
            userBill.setTitle("账户充值");
            // 明细种类：金额
            userBill.setCategory(BillDetailEnum.CATEGORY_1.getValue());
            // 明细类型：充值
            userBill.setType(BillDetailEnum.TYPE_1.getValue());
            // 1=获得
            userBill.setPm(1);
            // 明细数字
            userBill.setNumber(total);
            // 账户余额
            userBill.setBalance(balance);
            //创建时间
            userBill.setCreateTime(new Date());
            // 备注
            userBill.setMark("模拟充值：充值" + new_price + "元赠送" + new_giveMoney + "元");
            //添加账单信息
            userBillService.save(userBill);
        }
        return ResponseResult.okResult("充值成功");
    }
}
